<script>
import * as XLSX from 'xlsx';

function getPastelColor() {
  const baseColor = 255;
  const variation = 66;
  const r = baseColor - Math.floor(Math.random() * variation);
  const g = baseColor - Math.floor(Math.random() * variation);
  const b = baseColor - Math.floor(Math.random() * variation);
  return `rgb(${r}, ${g}, ${b})`;
}

export default {
  data() {
    return {
      weekDays: [
        { week: '周一' },
        { week: '周二' },
        { week: '周三' },
        { week: '周四' },
        { week: '周五' },
      ],
      timeSlots: [
        { section: 1, time: '09:00-10:20' },
        { section: 2, time: '10:40-12:00' },
        { section: 3, time: '12:30-13:50' },
        { section: 4, time: '14:00-15:20' },
        { section: 5, time: '15:30-16:50' },
        { section: 6, time: '17:00-18:20' },
        { section: 7, time: '19:00-20:20' },
        { section: 8, time: '20:30-21:50' }
      ],
      courses: [],
      courseGrid: [],
      debugText: ''
    };
  },

  methods: {
    processCoursesData() {
      const grid = Array(8).fill(null).map(() => Array(5).fill(null));
      this.courses.forEach(course => {
        if (course.section >= 1 && course.section <= 8 && course.day >= 0 && course.day <= 4) {
          if (!course.bgColor) {
            course.bgColor = getPastelColor();
          }
          grid[course.section - 1][course.day] = course;
        }
      });
      this.courseGrid = grid;
      this.debugText = JSON.stringify(this.courses);
    },

    importSchedule(event) {
      const file = event.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          const data = e.target.result;
          const workbook = XLSX.read(data, { type: 'binary' }); // 使用 XLSX.read
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          const jsonData = XLSX.utils.sheet_to_json(worksheet); // 使用 XLSX.utils
          const weekMap = {
            '周一': 0,
            '周二': 1,
            '周三': 2,
            '周四': 3,
            '周五': 4
          };
          const courses = jsonData.map(item => {
            const section = Number(item['节次']);
            const day = weekMap[item['星期']];
            const weeks = item['周数'].split(' ').map(week => Number(week));
            if (isNaN(section) || day === undefined) {
              return null;
            }
            return {
              name: (item['课程名称'] || '').trim(),
              code: (item['课程代码'] || '').trim(),
              teacher: (item['教师'] || '').trim(),
              room: (item['教室'] || '').trim(),
              day: day,
              section: section,
              weeks: weeks,
              bgColor: getPastelColor()
            };
          }).filter(course => course !== null);
          if (courses.length > 0) {
            this.courses = courses;
            this.processCoursesData();
            // 如果需要存储到本地，可以使用 localStorage 或其他存储方式
            localStorage.setItem('courses', JSON.stringify(courses));
            alert('导入成功');
          } else {
            alert('未找到有效数据');
          }
        };
        reader.readAsBinaryString(file);
      }
    },

    showCourseWeeks(course) {
      if (course && course.weeks) {
        const weeksString = course.weeks.join(', ');
        alert(`上课周数: ${weeksString}`);
      }
    }
  },

  mounted() {
    const storedCourses = localStorage.getItem('courses');
    if (storedCourses) {
      this.courses = JSON.parse(storedCourses);
      this.processCoursesData();
    } else {
      this.processCoursesData();
    }
  }
};
</script>

<template>
  <div class="page">
    <div class="schedule-container">
      <div class="week-row">
        <div class="time-header">
          <el-upload action="#" :auto-upload="false" :on-change="importSchedule" accept=".xlsx,.xls">
            <el-button slot="trigger" type="primary">选取文件</el-button>
          </el-upload>
        </div>
        <div class="week-cell" v-for="(item, index) in weekDays" :key="index">
          <span>{{ item.week }}</span>
        </div>
      </div>

      <div class="schedule-body">
        <div class="schedule-row" v-for="(item, index) in timeSlots" :key="index">
          <div class="time-cell">
            <span>{{ item.time }}</span>
            <span>第{{ item.section }}节</span>
          </div>
          <div class="day-cell" v-for="(dayIndex, idx) in [0,1,2,3,4]" :key="idx">
            <!-- 检查 courseGrid[item.section-1] 是否存在 -->
            <div v-if="courseGrid[item.section-1] && courseGrid[item.section-1][dayIndex]" class="course-info" :style="{ backgroundColor: courseGrid[item.section-1][dayIndex].bgColor }" @click="showCourseWeeks(courseGrid[item.section-1][dayIndex])">
              <span class="course-name">{{ courseGrid[item.section-1][dayIndex].name }}</span>
              <span class="course-room">{{ courseGrid[item.section-1][dayIndex].room }}</span>
              <span class="course-teacher">{{ courseGrid[item.section-1][dayIndex].teacher }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss">
.page {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.schedule-container {
  width: 100%;
  max-width: 800px;
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
}

.week-row {
  display: flex;
  border-bottom: 1px solid #ddd;
}

.time-header {
  background-color: #f0f0f0;
  border-right: 1px solid #ddd;
  padding: 8px;
  text-align: center;
  width: 150px;
}

.week-cell {
  background-color: #f0f0f0;
  border-right: 1px solid #ddd;
  padding: 8px;
  text-align: center;
  width: 150px;
}

.schedule-body {
  border-collapse: collapse;
  width: 100%;
}

.schedule-row {
  display: flex;
}

.time-cell {
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  padding: 8px;
  text-align: center;
  width: 150px;
}

.day-cell {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: center;
  position: relative;
}

.course-info {
  background-color: #fff;
  border: 1px solid #ddd;
  padding: 8px;
  cursor: pointer;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  transition: background-color 0.3s; /* 添加过渡效果 */
}

.course-name {
  font-weight: bold;
  text-align: center; /* 文本居中 */
}

.course-room,
.course-teacher {
  font-size: 0.9em;
  color: #555;
  text-align: center; /* 文本居中 */
}

.course-info:hover {
  background-color: #e0e0e0; /* 鼠标悬停时的背景颜色 */
}
</style>